package org.st.js4nk;

import cn.nukkit.Server;
import cn.nukkit.event.Event;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.*;


public class JSEvent {
    File jsfile = null;
    ScriptEngine nashorn;
    Invocable invocable;

    public JSEvent(File jsfile) {
        this.jsfile = jsfile;
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        nashorn = scriptEngineManager.getEngineByName("nashorn");
        invocable = (Invocable) nashorn;
        try {
            nashorn.eval(new BufferedReader(new InputStreamReader(new FileInputStream(jsfile), "UTF-8")));  //为了解决编码问题
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void call(Event event) {
        try {
            invocable.invokeFunction("onevent", event);
        } catch (ScriptException e) {
            Server.getInstance().getLogger().error(e.getMessage());
        } catch (NoSuchMethodException e) {
            Server.getInstance().getLogger().error("未找到监听器方法" + e.getMessage());
        }

    }
}
